package com.hbnu.jiani.service;

import com.hbnu.jiani.dao.UserDao;
import com.hbnu.jiani.dao.impl.UserDaoImpl;
import com.hbnu.jiani.entity.User;

import java.util.Optional;
import java.util.Scanner;

public class UserService {
    private UserDao userDao = new UserDaoImpl();
    private Scanner scanner = new Scanner(System.in);

    private static final String ADMIN_USERNAME = "admin";
    private static final String ADMIN_PASSWORD = "123456";

    public boolean register() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();
        if (username.isEmpty()) {
            System.out.println("用户名不能为空！");
            return false;
        }
        if ("admin".equalsIgnoreCase(username)) {
            System.out.println("错误：用户名 \"admin\" 为系统保留名称，不能用于注册！");
            return false;
        }
        if (userDao.findByUsername(username).isPresent()) {
            System.out.println("用户名已存在！");
            return false;
        }
        System.out.print("请输入密码: ");
        String password = scanner.nextLine().trim();
        if (password.isEmpty()) {
            System.out.println("密码不能为空！");
            return false;
        }
        User user = new User(username, password);
        if (userDao.registerUser(user)) {
            System.out.println("注册成功！");
            return true;
        } else {
            System.out.println("注册失败！");
            return false;
        }
    }


    public String userLogin() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        Optional<User> userOpt = userDao.findByUsername(username);
        if (userOpt.isPresent() && userOpt.get().getPassword().equals(password)) {
            System.out.println("用户登录成功！");
            return username;
        }

        System.out.println("用户名或密码错误！");
        return null;
    }


    public boolean adminLogin() {
        System.out.print("请输入管理员用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        if (ADMIN_USERNAME.equals(username) && ADMIN_PASSWORD.equals(password)) {
            System.out.println("管理员登录成功！");
            return true;
        } else {
            System.out.println("管理员用户名或密码错误！");
            return false;
        }
    }
}
